﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Security.Permissions;
using System.Configuration;
using IMTApp;

namespace IMTWindowsService
{
    public partial class FileWatcher : ServiceBase
    {
        
        string FolderWatchPath = @"C:\TSMSG\Input";
        //string MessageDelimiter = @",";
        int MessageDelimiterASCIIValue = 44;
        List<string> ProcessedFiles = new List<string>();

        public GPM.QuickQuote.Logging.GpmLogger logger = new GPM.QuickQuote.Logging.GpmLogger();
        

        [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
        public FileWatcher()
        {
           
                logger.LogInfo("WINDOWS SERVIVCE:In File Watcher");
                AppDomain currentDomain = AppDomain.CurrentDomain;
                currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);

                try
                {
                    logger.LogInfo("WINDOWS SERVIVCE:In try/catch block");
                    InitializeComponent();

                    startFileWatcher();
                }
                catch (Exception e)
                {
                    logger.LogInfo("EXCEPTION Windows Service: " + e);
                }
           
        }

         static void MyHandler(object sender, UnhandledExceptionEventArgs args)
         {
             GPM.QuickQuote.Logging.GpmLogger logger = new GPM.QuickQuote.Logging.GpmLogger();

             Exception e = (Exception)args.ExceptionObject;
             logger.LogInfo("MyHandler caught : " + e.Message);
         }


        protected override void OnStart(string[] args)
        {
            
               // startFileWatcher();
            
        }

       

        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        private void startFileWatcher()
        {

            logger.LogInfo("In startFileWatcher()");

            FileSystemWatcher watcher = new FileSystemWatcher();

            watcher.Path = FolderWatchPath;

            watcher.Filter = "*.txt";

            watcher.NotifyFilter = NotifyFilters.LastAccess |
                                   NotifyFilters.LastWrite |
                                   NotifyFilters.FileName |
                                   NotifyFilters.DirectoryName;

            watcher.IncludeSubdirectories = false;


            watcher.Created += new FileSystemEventHandler(OnChanged);
            logger.LogInfo("Created OnChanged Event Handler");

            watcher.Renamed += new RenamedEventHandler(OnChanged);

            watcher.EnableRaisingEvents = true;

            logger.LogInfo("End of startFileWatcher()");

        }

        public void OnChanged(object Sender, FileSystemEventArgs e)
        {
            logger.LogInfo(" ");
            logger.LogInfo(" ");
            logger.LogInfo(" ");
            logger.LogInfo("**********************************************************************************");
            logger.LogInfo("IMTWindowsService:OnChanged Event Entered");
            logger.LogInfo("");
            //we should save the file path in a list, then compare the incomming e.fullpath to the list to see if it exists

            System.Threading.Thread.Sleep(5000);
            

            //Check if the message has already been processed
            if (ProcessedFiles.Contains(e.FullPath.ToString()))
            {
                logger.LogInfo("Duplicate Message Processed");
            }
            else
            {
                //add file to ProcessedFiles list
                ProcessedFiles.Add(e.FullPath.ToString());
                logger.LogInfo("New File Found");
                logger.LogInfo("Contents are");
                logger.LogInfo(string.Join(",",ProcessedFiles.ToArray()));

                try
                {
                    StringBuilder inputString = new System.Text.StringBuilder();

                    using (StreamReader reader = new StreamReader(e.FullPath))
                    //using(FileStream reader = new FileStream(e.FullPath,FileMode.Open, FileAccess.Read, FileShare.Read);
                    {
                     
                        while (reader.Peek() != MessageDelimiterASCIIValue)
                        { 
                            inputString.Append(char.ConvertFromUtf32(reader.Read()));
                        }
                        reader.Close();
                        reader.Dispose();
                    }

                    switch (inputString.ToString())
                    {


                        case "SUBMITENDORSEMENT":
                            logger.LogInfo("Found SUBMITENDORSEMENT Msg type");
                            SubmitEndorsementMsg Message = new SubmitEndorsementMsg(e.FullPath.ToString());
                            break;

                        case "QUERYENDORSEMENT":
                            logger.LogInfo("Found QUERYENDORSEMENT Msg type");
                            QueryEndorsementMSG QEMessage = new QueryEndorsementMSG(e.FullPath.ToString());
                            break;

                        default:
                            break;
                    }


                }
                catch (Exception f)
                {
                    logger.LogInfo("DEBUG: " + f);
                }
            }

        }

        private void OnRenamed(object source, RenamedEventArgs e)
        {
            logger.LogInfo(" ");
            logger.LogInfo(" ");
            logger.LogInfo(" ");
            logger.LogInfo("**********************************************************************************");
            logger.LogInfo("IMTWindowsService: OnRename Event Entered");

            //we should save the file path in a list, then compare the incomming e.fullpath to the list to see if it exists

            System.Threading.Thread.Sleep(5000);
           
            if (ProcessedFiles.Contains(e.FullPath.ToString()))
            {
                logger.LogInfo("Duplicate Message Processed");
            }
            else
            {
                //add file to ProcessedFiles list
                ProcessedFiles.Add(e.FullPath.ToString());
                logger.LogInfo("New Rename Found");
                logger.LogInfo("Contents are");
                logger.LogInfo(string.Join(",", ProcessedFiles.ToArray()));

                try
                {
                    StringBuilder inputString = new System.Text.StringBuilder();

                    using (StreamReader reader = new StreamReader(e.FullPath))
                    //using(FileStream reader = new FileStream(e.FullPath,FileMode.Open, FileAccess.Read, FileShare.Read);
                    {

                        while (reader.Peek() != MessageDelimiterASCIIValue)
                        {
                            inputString.Append(char.ConvertFromUtf32(reader.Read()));
                        }
                        reader.Close();
                        reader.Dispose();
                    }

                    switch (inputString.ToString())
                    {


                        case "SUBMITENDORSEMENT":
                            logger.LogInfo("Found SUBMITENDORSEMENT Msg type");
                            SubmitEndorsementMsg Message = new SubmitEndorsementMsg(e.FullPath.ToString());
                            break;
                        case "QUERYENDORSEMENT":
                            logger.LogInfo("Found QUERYENDORSEMENT Msg type");
                            QueryEndorsementMSG QEMessage = new QueryEndorsementMSG(e.FullPath.ToString());
                            break;
                          
                        default:
                            break;
                    }


                }
                catch (Exception f)
                {
                    logger.LogInfo("DEBUG: " + f);
                }
            }
        }

        protected override void OnStop()
        {
        }

       

       
    }
   
}
